import { type Device } from "react-native-ble-plx";
import {
  Platform,
  PermissionsAndroid,
  RefreshControl,
  Text,
  ScrollView,
  View,
} from "react-native";
import { useEffect, useState, useCallback } from "react";
import { manager } from "utils/bleManage";
import { setStorageData } from "utils";
import toast from "utils/toast";
import translate from "utils/translate";
import { useFocusEffect } from "@react-navigation/native";
const requestBluetoothPermission = async () => {
  if (Platform.OS === "ios") {
    return true;
  }
  if (
    Platform.OS === "android" &&
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
  ) {
    const apiLevel = parseInt(Platform.Version.toString(), 10);

    if (apiLevel < 31) {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
      );
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    }
    if (
      PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN &&
      PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT
    ) {
      const result = await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
        PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      ]);

      return (
        result["android.permission.BLUETOOTH_CONNECT"] ===
          PermissionsAndroid.RESULTS.GRANTED &&
        result["android.permission.BLUETOOTH_SCAN"] ===
          PermissionsAndroid.RESULTS.GRANTED &&
        result["android.permission.ACCESS_FINE_LOCATION"] ===
          PermissionsAndroid.RESULTS.GRANTED
      );
    }
  }
  toast(translate("home.bind.tip6"));
  return false;
};
export default ({ navigation }: RootStackScreenProps) => {
  const bleList: Device[] = [];
  const [tip, setTip] = useState(translate("main.loading") + "...");
  const [refreshing, setRefreshing] = useState(false);
  useEffect(() => {
    requestBluetoothPermission().then((value) => {
      value && onSearch();
    });
  }, []);
  useEffect(() => {
    const unsubscribe = navigation.addListener("beforeRemove", () => {
      if (timer) {
        clearTimeout(timer);
      }
    });
    return () => {
      unsubscribe();
    };
  }, [navigation]);
  let timer: number;
  const onSearch = () => {
    manager.state().then((value) => {
      if (value !== "PoweredOn") return toast(translate("home.bind.enabled"));
      manager.startDeviceScan(null, null, (_, device: Device | null) => {
        if (device?.id && device.name) {
          bleList.push(device);
        }
      });
      timer = setTimeout(() => {
        toast(translate("main.success"));
        manager.stopDeviceScan();
        const uniqueArray = Array.from(
          bleList
            .reduce((accumulator, currentValue) => {
              const key = currentValue.id; // Customize the key based on your object structure
              if (!accumulator.has(key)) {
                accumulator.set(key, currentValue);
              }
              return accumulator;
            }, new Map())
            .values()
        );
        if (uniqueArray.length > 0) {
          setStorageData("deviceList", JSON.stringify(uniqueArray)).then(() => {
            setTimeout(() => {
              navigation.replace("bleList", {});
            }, 2000);
          });
        } else {
          setTip(translate("home.bind.tip5"));
        }
        setRefreshing(false);
      }, 1000 * 4);
    });
  };
  const onRefresh = useCallback(() => {
    setRefreshing(true);
    onSearch();
  }, []);
  return (
    <View style={{ flex: 1 }}>
      <ScrollView
        style={{ flex: 1 }}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        contentContainerStyle={{
          alignItems: "center",
          justifyContent: "center",
          flex: 1,
        }}
      >
        <Text>{tip}</Text>
        <Text
          style={{
            marginTop: 10,
            color: "rgba(0, 0, 0, 0.60)",
          }}
        >
          {translate("home.bind.tip7")}
        </Text>
        <Text
          style={{
            marginTop: 10,
            marginBottom: 10,
            color: "rgba(0, 0, 0, 0.60)",
          }}
        >
          {translate("home.bind.tip2")}
        </Text>
        <Text style={{ color: "rgba(0, 0, 0, 0.60)" }}>
          {translate("home.bind.tip1")}
        </Text>
      </ScrollView>
    </View>
  );
};
